package cn.itcast.mq.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class SpringRabbitListener {

    //    @RabbitListener(queues = "simple.queue")
//    public void listenSimpleQueue(String msg) {
//        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
//
//        // 出bug了
//        System.out.println(1/0);
//
//        System.out.println("消费者  消费了消息");
//    }
//    @RabbitListener(queues = "simple.queue")
//    public void listenSimpleQueue(@Payload String msg, Channel channel, Message message) {
//        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
//        // 出bug了
////        System.out.println(1 / 0);
//
//        System.out.println("消费者  消费了消息");
//
//        // 手动确认消息
//        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue(String msg) {
        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】" + LocalDateTime.now().toString());
        // 出bug了
        System.out.println(1 / 0);
        System.out.println("消费者  消费了消息");
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("dl.queue"),   // 队列
            exchange =  @Exchange(value = "dl.direct",type = "direct"),  // 交换机
            key = {"dl"}
    ))
    public void listenDLQueue(String msg) {
        System.out.println("消费者接收到dl.queue的消息：【" + msg + "】  " + LocalDateTime.now().toString());
    }

    /**
     *    queues :  仅仅是监听队列
     *
     *    queuesToDeclare  监听队列  如果队列不存在就创建
     *
     *    bindings  监听队列  可以创建出相关的 交换机  队列  和  绑定关系
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("delay.queue") ,
            exchange = @Exchange(value = "delay.direct",delayed = "true"),
            key = "delay"
    ))
    public void listenDelayedQueue(String msg) {
        System.out.println("消费者接收到delay.queue的消息：【" + msg + "】  " + LocalDateTime.now().toString());
    }
}
